<template>
  <a-tree-select
    v-model="myValue"
    style="width: 100%"
    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
    placeholder="请选择处置单位"
    :treeData="treeData"
    :replaceFields="{ children: 'children', title: 'name', value: 'id' }"
    searchPlaceholder="输入关键字搜索"
    :showSearch="true"
    :filterTreeNode="filterOption"
    @change="deptTreechange"
  >
  </a-tree-select>
</template>

<script>
import { findUserTree } from '@/api/base/ha_user'

export default {
  props: {
    // 登录人部门
    departid: {
      type: String,
      require: true,
    }
  },
  data() {
    return {
      myValue: this.departid || null,
      treeData: [],
    }
  },
  created() {
    this.queryDeput(this.departid)
  },
  methods: {
    // 父组件调用重设值
    f_setValue(value) {
      this.myValue = value
    },
    // 下拉框搜索
    filterOption(input, option) {
      return option.data.props.name.indexOf(input) >= 0
    },
    // 树选中
    deptTreechange(value, label, extra) {
      let result = []
      this.recursionDeptid(result, this.myValue, this.treeData)
      this.$emit('f_deptTreechange', result)
      console.log('树选中', result)
    },
    // 递归查询当前节点的id和他的下级id
    recursionDeptid(result, id, treeData, isSave = false) {
      treeData.map(v => {
        if(v.id == id || isSave) {
          result.push(v.id)
          this.recursionDeptid(result, id, v.children, true)
          return
        }
        if(v.children && v.children.length > 0) {
          this.recursionDeptid(result, id, v.children)
        }
      })
    },
    // 查询单位列表
    async queryDeput(departid) {
      const { data } = await findUserTree(departid, { type: 1, isuser: false })
      // console.log('处置部门', data)
      this.treeData = data || []
    },
  },
}
</script>

<style lang="scss" scoped>
</style>
